/*
 * 此处无法调用 getApp
 * */
import CONFIG from './config'
import transDate from './modules/transDate'
import getTerm from './modules/getTerm'
import getFileType from './modules/getFileType'
import historyPage from './modules/historyPage'
import downImg from './modules/downImg'
import downHttpImg from './modules/downHttpImg'
import queryStringify from './modules/queryStringify'
import uuid from './modules/uuid'
import dayjs from '../plugin/dayjs/index'
import { LOCAL } from '../config/variable'

// 时间格式化
function formatTime (date = new Date()) {
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

function formatOnlyTime (timeStr) {
    let date = new Date(timeStr)
    return dayjs(date).format('HH:mm:ss')
}

/**
 * @deprecated 未处理兼容性问题 废弃
 * @param {*} date
 * @param {*} pattern
 * @returns
 */
function formatDate (date = new Date(), pattern = 'YYYY-MM-DD') {
    return dayjs(date).format(pattern)
}

function dateFromat (dateStr, pattern = 'YYYY-MM-DD') {
    if (!dateStr) {
        return ''
    }

    dateStr = dateStr.replace(/-/g, '/')
    dateStr = dateStr.replace(/\./g, '/')

    const date = new Date(dateStr)
    return dayjs(date).format(pattern)
}

/**
 * 输入的时间格式为yyyy-MM-dd
 * @params  dateStr
 */
function stringFormatDate (dateStr) {
    if (dateStr) {
        return new Date(dateStr.replace(/-/, '/'))
    }
}

/**
 * 输入的时间格式为yyyy-MM-dd hh:mm:ss
 * @params  dateStr
 */
function convertDateFromString (dateStr) {
    if (dateStr) {
        let arr1 = dateStr.split(' ')
        let sdate = arr1[0].split('-')
        let date = new Date(sdate[0], sdate[1] - 1, sdate[2])
        return date
    }
}

/**
 * 获取时间是周几
 */
function getWeek (date = new Date()) {
    let weekDay = [
        '星期天',
        '星期一',
        '星期二',
        '星期三',
        '星期四',
        '星期五',
        '星期六'
    ]
    return weekDay[date.getDay()]
}
/**
 * [encodeUrlParam 编码参数]
 * @param  {[type]} url      [页面对应的url] 如 '../report/main'
 * @param  {[type]} paramObj [参数对象] 如 {code:100}
 * @return {[type]}          [description]
 */
function encodeUrlParam (url, paramObj = {}) {
    let params = ''
    if (paramObj) {
        let keys = Object.keys(paramObj)
        for (let key of keys) {
            let val = paramObj[key]
            if (val) {
                if (typeof val === 'object') {
                    val = JSON.stringify(val)
                }
                val = encodeURIComponent(val)
            }
            params += `${key}=${val}&`
        }
    }
    if (params) {
        params = params.substr(0, params.length - 1)
    }
    if (params) {
        return `${url}?${params}`
    }
    return url
}

/**
 * [decodeUrlParam 解码参数]
 * @param  {[type]} paramObj [参数对象]
 * @return {[type]}          [description]
 */
function decodeUrlParam (paramObj = {}) {
    if (paramObj && typeof paramObj === 'object') {
        let keys = Object.keys(paramObj)
        for (let key of keys) {
            let val = paramObj[key]
            if (val) {
                let strVal = decodeURIComponent(val)
                try {
                    paramObj[key] = JSON.parse(strVal)
                } catch (ex) {
                    paramObj[key] = strVal
                }
            }
        }
    }
    return paramObj
}

function urlArgsToJson (str) {
    let src = decodeURIComponent(str)
    console.log('url-src', src)
    let args = {}
    let items = src.length > 0 ? src.split('&') : []
    let item = null
    let name = null
    let value = null
    for (let i = 0; i < items.length; i++) {
        item = items[i].split('=')
        name = decodeURIComponent(item[0])
        value = decodeURIComponent(item[1])
        if (name.length) {
            args[name] = value
        }
    }
    console.log('args----', args)
    return args
}

/**
 * 设置Uc 需要使用的token
 * @param {*} token
 */
export const setUcTokenAndId = (token, userid) => {
    wx.setStorageSync('userToken', token)
    wx.setStorageSync(LOCAL.UC.TOKEN, token)
    wx.setStorageSync(LOCAL.UC.USERID, userid)
}

export const isNull = val => {
    return [undefined, null, 'undefined', 'null', ''].includes(val)
}

export const setUserInfo = userInfoNew => {
    if (isNull(userInfoNew)) {
        return false
    }

    const userInfo = wx.getStorageSync(LOCAL.USERINFO)
    Object.assign(userInfo, userInfoNew)

    // console.log(userInfo)
    wx.setStorageSync(LOCAL.USERINFO, userInfo)
}

/**
 * 计算时间差
 * @param starttime 开始时间
 * @param endtime 结束时间
 * */
export function timeDifference (starttime, endtime) {
    let startDate = new Date(starttime).getTime()
    let endDate = new Date(endtime).getTime()
    let dateCha = endDate - startDate
    //计算出相差天数
    let days = Math.floor(dateCha / (24 * 3600 * 1000))
    //计算出小时数
    let leave1 = dateCha % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    let hours = Math.floor(leave1 / (3600 * 1000))
    //计算相差分钟数
    let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
    let minutes = Math.floor(leave2 / (60 * 1000)) // 分
    //计算相差秒数
    let leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
    let seconds = Math.round(leave3 / 1000) // 秒
    // console.log(days + '天 ' + hours + '小时 ')

    let str = ''
    if (days) {
        str += `${days}天`
    }

    if (hours) {
        str += `${hours}时`
    }

    if (minutes) {
        str += `${minutes}分`
    }

    if (seconds) {
        str += `${seconds}秒`
    }

    return {
        days,
        hours,
        minutes,
        seconds,
        longText: str
    }
}

export default {
    formatTime,
    formatOnlyTime,
    stringFormatDate,
    convertDateFromString,
    getWeek,
    dateFromat,
    // json转form
    formatDate,
    queryStringify,
    encodeUrlParam,
    decodeUrlParam,
    urlArgsToJson,
    isIpx () {
        const sysInfo = wx.getSystemInfoSync()
        const { model } = sysInfo
        // console.log(sysInfo, '===手机型号===')
        let arr = ['iPhone X', 'iPhone XS', 'iPhone XS Max', 'iPhone XR']
        // 截止到2021年12月3号
        const newArr = ['iPhone 11', 'iPhone 12', 'iPhone 13', 'unknown']
        let isIpx = false
        arr = [...arr, ...newArr]

        arr.forEach(item => {
            if (model.includes(item)) {
                isIpx = true
            }
        })
        return isIpx
    },
    isJson (str) {
        try {
            JSON.parse(str)
            return true
        } catch (e) {
            return false
        }
    },
    // 缓存操作
    store: {
        get: key => {
            const data = wx.getStorageSync(key)
            try {
                return JSON.parse(data)
            } catch (e) {
                return data
            }
        },
        set: (key, data) => {
            if (typeof data === 'object') {
                wx.setStorageSync(key, data)
            }
        }
    },
    // 富文本格式化
    htmlFormatForSel: text => {
        //console.log(text);
        let newContent = text.replace(/<img[^>]*>/gi, (match, capture) => {
            //console.log(match);
            // return match.replace(/style=\"(.*)\"/gi, 'style=""');
            if (match.includes('style=')) {
                return match.replace(
                    /style=\"(.*)\"/gi,
                    'style="width:100%;display:block;"'
                )
            } else {
                return match.replace(
                    /<img/gi,
                    '<img class="img" style="width:100%;display:block;" '
                )
            }
        })
        var imgReg = /<img.*?(?:>|\/>)/gi
        var arr = newContent.match(imgReg)
        let imgStr = ''
        if (arr) {
            for (var i = 0; i < arr.length; i++) {
                //console.log(arr[i]);
                imgStr += arr[i]
            }
        }
        newContent = imgStr
        //return str
        return newContent
    },
    // 富文本格式化
    htmlFormat: text => {
        let newContent = text.replace(/<img[^>]*>/gi, (match, capture) => {
            // return match.replace(/style=\"(.*)\"/gi, 'style=""');
            if (match.includes('style=')) {
                return match.replace(
                    /style=\"(.*)\"/gi,
                    'style="width:100%;display:block;"'
                )
            } else {
                return match.replace(
                    /<img/gi,
                    '<img class="img" style="width:100%;display:block;" '
                )
            }
        })
        newContent = text.replace(/<br>/gi, (match, capture) => {
            return match.replace(/<br>/gi, '<div style="height: 15px;"></div>')
        })
        return newContent

        //return text.replace(/style=\"(.*)\"/gi, 'style=""')
        //return text;
    },
    // 富文本换行符转为br标签
    htmlBrStyle: (text, brCount = 1) => {
        let br = ''
        for (let i = 0; i < brCount; i++) {
            br += '<br>'
        }
        return text.replace(/\n/gi, br)
    },
    // 字符串截取
    textSplice (text = '', number = 0) {
        if (text && number > 0) {
            if (text.length > number) {
                return '...'.padStart(number + 3, text)
            }
            return text
        } else {
            return text
        }
    },
    // 动态获取指定日期
    getDate: (date, diffVal, time) => {
        let now
        if (date) {
            now = new Date(date)
        } else {
            now = new Date()
        }
        now.setTime(now.getTime() + diffVal) // 第二天的日期
        let y = now.getFullYear(),
            m = now.getMonth() + 1,
            d = now.getDate(),
            h = now.getHours(), //获取当前小时数(0-23)
            f = now.getMinutes(),
            n = Math.ceil(now.getMinutes() / 10) * 10 //获取当前分钟数(0-59)  取整数
        return (
            y +
            '/' +
            (m < 10 ? '0' + m : m) +
            '/' +
            (d < 10 ? '0' + d : d) +
            ' ' +
            time
        )
    },
    imgReg: str => {
        var imgReg = /<img.*?(?:>|\/>)/gi
        //匹配src属性
        var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
        var arr = str.match(imgReg)
        if (arr) {
            for (var i = 0; i < arr.length; i++) {
                var src = arr[i].match(srcReg)
                //获取图片地址
                if (src[1]) {
                    var regHttp = new RegExp('^http')
                    if (!regHttp.test(src[1])) {
                        console.log(
                            '已匹配的图片地址' + (i + 1) + '：' + src[1]
                        )
                        let url = 'http://mirror.laikang.com' + src[1]
                        str = str.replace(src[1], url)
                    }
                }
            }
        }
        return str
    },
    // 获取文件类型
    fileType: getFileType,
    getDeFen: text => {
        try {
            if (text.includes('得分')) {
                return Number(text.split('，')[0].split('：')[1])
            } else {
                return null
            }
        } catch (e) {
            return null
        }
    },
    // 历史访问页面操作
    historyPage,
    // 生成小程序码
    createMiniQrCode (path) {
        const p = encodeURIComponent(path)
        return `${CONFIG.baseURL}/api/wxapp/qrcode/${CONFIG.orgCode}/billboardapp?shape=circular&path=${p}`
    },
    // 下载临时文件路径或永久文件路径，不支持网络图片路径
    downImg,
    // 下载网络图片至本地
    downHttpImg,
    /**
     * todo
     * 查询用户授权情况，未授权将会跳转至授权页，引导用户设置
     * @param {String} name 授权列表
     * userLocation:地理位置
     * address:通讯地址
     * invoiceTitle:发票抬头
     * invoice:获取发票
     * werun:微信运动步数
     * record:录音功能
     * writePhotosAlbum:保存到相册
     * camera:摄像头
     * */
    getSetting (name) {
        if (!list.length) {
            return
        }
    },
    /**
     * 复制文字
     * */
    copyText (data) {
        return new Promise((resolve, reject) => {
            if (!data) {
                reject({
                    message: '文字为空，复制失败'
                })
                return
            }
            wx.setClipboardData({
                data,
                success: res => {
                    console.log(res)
                    resolve(res)
                },
                fail: e => {
                    console.error(e)
                    reject(e)
                }
            })
        })
    },
    transDate,
    getTerm,
    uuid,
    sleep: (timer = 0) => {
        if (timer > 0) {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve()
                }, timer)
            })
        }
    },
    getAge (strAge) {
        var birArr = strAge.split('-')
        var birYear = birArr[0]
        var birMonth = birArr[1]
        var birDay = birArr[2]

        d = new Date()
        var nowYear = d.getFullYear()
        var nowMonth = d.getMonth() + 1 //记得加1
        var nowDay = d.getDate()
        var returnAge

        if (birArr == null) {
            return false
        }
        var d = new Date(birYear, birMonth - 1, birDay)
        if (
            d.getFullYear() == birYear &&
            d.getMonth() + 1 == birMonth &&
            d.getDate() == birDay
        ) {
            if (nowYear == birYear) {
                returnAge = 0 //
            } else {
                var ageDiff = nowYear - birYear //
                if (ageDiff > 0) {
                    if (nowMonth == birMonth) {
                        var dayDiff = nowDay - birDay //
                        if (dayDiff < 0) {
                            returnAge = ageDiff - 1
                        } else {
                            returnAge = ageDiff
                        }
                    } else {
                        var monthDiff = nowMonth - birMonth //
                        if (monthDiff < 0) {
                            returnAge = ageDiff - 1
                        } else {
                            returnAge = ageDiff
                        }
                    }
                } else {
                    return '出生日期晚于今天，数据有误' //返回-1 表示出生日期输入错误 晚于今天
                }
            }
            return returnAge
        } else {
            return '输入的日期格式错误！'
        }
    },
    validatePhone: value => {
        // 正则表达式
        if (!/^1[3456789]\d{9}$/.test(value)) {
            return false
        }
        return true
    }
}
